package com.zdkj.subway.check.controller.subwayRat.conductorDifferences.cheZhan;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.check.controller.CommonController;
import com.zdkj.subway.check.entity.*;
import com.zdkj.subway.check.enums.ResultDetailMsg;
import com.zdkj.subway.check.mapper.SwAuStDiffNoticeMapper;
import com.zdkj.subway.check.mapper.SwAuStationShortMapper;
import com.zdkj.subway.check.mapper.SwAuStationTicketDifferenceMapper;
import com.zdkj.subway.check.result.Result;
import com.zdkj.subway.check.util.CheckAccount;
import com.zdkj.subway.check.util.DateFormat;
import com.zdkj.subway.check.util.UserInfo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 车站差异确认通知
 */
@Slf4j
@RestController
@RequestMapping("/check")
public class SwAuStDiffNoticeController {

    @Resource
    SwAuStDiffNoticeMapper swAuStDiffNoticeMapper;
    @Resource
    SwAuStationShortMapper swAuStationShortMapper;
    @Autowired
    private CommonController commonController;
    @Resource
    SwAuStationTicketDifferenceMapper swAuStationTicketDifferenceMapper;
    /**
     * 车站票款差异确认通知查询
     * @param page
     * @param swAuStDiffNotice
     * @param param
     * @return
     */
    @RequestMapping("/getSwAuStDiffNoticeList")
    @ApiOperation(value = "车站票款差异确认通知查询", notes = "车站票款差异确认通知查询")
    public Page getSwAuStDiffNoticeList(Page page, SwAuStDiffNotice swAuStDiffNotice, @RequestParam Map<String,String> param){
        List<Map<String,Object>> res=swAuStDiffNoticeMapper.getSwAuStDiffNoticeList(param);
        page.setData(res,true);
        return page;
    }

    /**
     * 设置回复期限
     * @param swAuStDiffNotice
     * @return
     */
    @RequestMapping("/setSwAuStDiffNoticeReplyPeriod")
    @ApiOperation(value = "设置回复期限", notes = "设置回复期限")
    public Result setSwAuStDiffNoticeReplyPeriod(String ids, SwAuStDiffNotice swAuStDiffNotice){
        Result res=new Result(ResultDetailMsg.OK);
        try {
            List<SwAuStDiffNotice> swAuStDiffNotices = swAuStDiffNoticeMapper.selectBatchIds(Arrays.asList(ids.split(",")));
            for(SwAuStDiffNotice s:swAuStDiffNotices){
                Date sendTime = new Date();
                sendTime=s.getSendTime();
                if(sendTime!=null){
                    Date date = DateFormat.date_add_or_sub_days(sendTime, swAuStDiffNotice.getReplyPeriod());
                    if(date.compareTo(new Date())>=0){ //超期限申诉
                        s.setAppealType("1");
                    }else{
                        s.setAppealType("2");
                    }
                }
                s.setReplyPeriod(swAuStDiffNotice.getReplyPeriod());
                swAuStDiffNoticeMapper.updateById(s);
            }
        }catch (Exception e){
            log.error("{}",e);
            res.setMsg("设置回复期限天数失败");
            res.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
        }
        return res;
    }

    /**
     * 下发
     * @param param
     * @return
     */
    @RequestMapping("/sendSwAuStDiffNoticeStatusUpdate")
    @ApiOperation(value = "下发", notes = "下发")
    @Transactional(rollbackFor = Exception.class)
    public Result sendSwAuStDiffNoticeStatusUpdate(@RequestBody Map<String,Object> param){
        String ids = String.valueOf(param.get("ids"));
        Result res=new Result(ResultDetailMsg.OK);
        try {
            UpdateWrapper<SwAuStDiffNotice> updateWrapper=new UpdateWrapper<>();
            updateWrapper.in("id",ids.split(","));
            SwAuStDiffNotice swAuStDiffNotice = new SwAuStDiffNotice();
            //下发状态 已下发
            swAuStDiffNotice.setSendState("1");
            swAuStDiffNotice.setSendTime(new Date());
            swAuStDiffNotice.setAppealState("1");//下发时默认待申诉
            swAuStDiffNoticeMapper.update(swAuStDiffNotice,updateWrapper);
            commonController.innerBatch(param);
        }catch (Exception e){
            log.error("{}",e);
            res.setMsg("下发失败");
            res.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return res;
    }

    /**
     * 支持批量审批
     * @param s
     * @return
     */
    @RequestMapping("/approveDataSwAuStDiffNotice")
    @ApiOperation(value = "支持批量审批", notes = "支持批量审批")
    public Result approveDataSwAuStDiffNotice( String ids, SwAuStDiffNotice s){
        Result res=new Result(ResultDetailMsg.OK);
        try {
            if(s.getApproverName()==null){
                PigxUser user = SecurityUtils.getUser();
                s.setApproverName(user.getNikeName());//审批人
                s.setApproverJob(user.getUserCode());//审批人工号
                s.setApproverTime(new Date());//审批时间
            }
            if("2".equals(s.getAuditSate())&&!"6".equals(s.getAppealState())){
                s.setAppealState("3");//申诉成功
            }else if("3".equals(s.getAuditSate())&&!"6".equals(s.getAppealState())){
                s.setAppealState("4");//申诉失败
            }
            List<SwAuStDiffNotice> swAuStDiffNotices = swAuStDiffNoticeMapper.selectBatchIds(Arrays.asList(ids.split(",")));
            //TODO 如果是超期申诉审批通过，也同时查找是否存在补款信息数据，存在进行删除
            if("2".equals(s.getAuditSate())){
                LambdaQueryWrapper<SwAuStationShort> wrapper =
                        Wrappers.<SwAuStationShort>lambdaQuery().in(SwAuStationShort::getRelationid, Arrays.asList(ids.split(",")));
                swAuStationShortMapper.delete(wrapper);
            }
			int supPaymentLimit = CheckAccount.getLimitTime("STATION_REPLENISH_validity");
            /*
			String sw_pm_time_sql = "select * from sw_pm_time";
            List<Map<String, Object>> sw_pm_time_resp = JdbcUtil.exeSqlQuery(sw_pm_time_sql);
            Object conductorReplenishValidity = sw_pm_time_resp.get(0).get("CONDUCTOR_REPLENISH_validity");
            */
			for(SwAuStDiffNotice swAuStDiffNotice:swAuStDiffNotices){
                s.setId(swAuStDiffNotice.getId());
                swAuStDiffNoticeMapper.updateById(s);

                if("3".equals(s.getAuditSate())){ //审批不通过,加入车站补款通知
                    SwAuStationShort swAuStationShort=new SwAuStationShort();
                    //关联id
                    swAuStationShort.setRelationid(swAuStDiffNotice.getId());
                    //线路
                    swAuStationShort.setLineCode(swAuStDiffNotice.getLineCode());
                    //站点
                    swAuStationShort.setStationCode(swAuStDiffNotice.getStationCode());
                    //售票员工号
                    swAuStationShort.setConductorJobNo(swAuStDiffNotice.getConductorJobNo());
                    swAuStationShort.setConductorPersonName(swAuStDiffNotice.getConductorPersonName());
                    //收入日期
                    swAuStationShort.setIncomeTime(swAuStDiffNotice.getIncomeTime());
                    //TODO 审批不通过 根据线路、车站、售票员、收益日期四个条件判断如果之前存在补款信息，将数据进行更新
                    QueryWrapper<SwAuStationShort> query = Wrappers.query(swAuStationShort);
                    SwAuStationShort serviceOne = swAuStationShortMapper.selectOne(query);
                    if(ObjectUtil.isNotEmpty(serviceOne)){
                        swAuStationShort.setId(serviceOne.getId());
                    }
                    //短款金额
                    swAuStationShort.setShortAmount(swAuStDiffNotice.getDiffAmount().abs());
                    swAuStationShort.setConductorConfirmStatus("");
                    //通知状态未通知
                    swAuStationShort.setNoticeState("0");
                    swAuStationShort.setNoticeTime(null);
                    swAuStationShort.setIsNotice(0); //该字段住注释为是否补款？
                    swAuStationShort.setExtraMoneyTime(null);
                    swAuStationShort.setAccountTime(null);
                    swAuStationShort.setCreatorId(UserInfo.getId());
                    swAuStationShort.setCreatorName(UserInfo.getUserName());
                    swAuStationShort.setCreateTime(new Date());
                    swAuStationShort.setUpdateTime(new Date());
                    swAuStationShort.setSupPaymentLimit(supPaymentLimit);//补款期限
                    int i = swAuStDiffNotice.getDiffAmount().compareTo(new BigDecimal("0"));
                    //差异金额小于0时才加入到补款通知
                    if( i == -1){
                        if(swAuStationShort.getId() != null){
                            swAuStationShortMapper.updateById(swAuStationShort);
                        }else {
                            swAuStationShortMapper.insertSwAuStationShort(swAuStationShort);
                        }
                    }
                }
            }

        }catch (Exception e){
            log.error("{}",e);
            res.setMsg("审批失败");
            res.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
        }
        return res;
    }

    /**
     * 通知数据
     * @param ids
     * @return
     */
    @RequestMapping("/noticeSwAuStDiffNotice")
    @ApiOperation(value = "通知数据", notes = "通知数据")
    public Result noticeSwAuStDiffNotice( String ids){
        Result res=new Result(ResultDetailMsg.OK);
        try {
            for(String id:ids.split(",")){
                SwAuStDiffNotice swAuStDiffNotice = swAuStDiffNoticeMapper.selectById(Integer.parseInt(id));
                SwAuStationShort swAuStationShort=new SwAuStationShort();
                //关联id
                swAuStationShort.setRelationid(swAuStDiffNotice.getId());
                //线路
                swAuStationShort.setLineCode(swAuStDiffNotice.getLineCode());
                //站点
                swAuStationShort.setStationCode(swAuStDiffNotice.getStationCode());
                swAuStationShort.setConductorJobNo(swAuStDiffNotice.getConductorJobNo());
                swAuStationShort.setConductorPersonName(swAuStDiffNotice.getConductorPersonName());
                //收入日期
                swAuStationShort.setIncomeTime(swAuStDiffNotice.getIncomeTime());
                //差异金额
                swAuStationShort.setShortAmount(swAuStDiffNotice.getDiffAmount());
                //售票员确认状态
                swAuStationShort.setConductorConfirmStatus("");
                //通知状态
                swAuStationShort.setNoticeState("0");
                swAuStationShort.setNoticeTime(null);
                swAuStationShort.setIsNotice(0); //该字段住注释为是否补款？
                swAuStationShort.setExtraMoneyTime(null);
                swAuStationShort.setAccountTime(null);
                swAuStationShort.setCreatorId(UserInfo.getId());
                swAuStationShort.setCreatorName(UserInfo.getUserName());
                swAuStationShort.setCreateTime(new Date());
                swAuStationShort.setUpdateTime(new Date());

                swAuStationShortMapper.insertSwAuStationShort(swAuStationShort);

                swAuStDiffNotice.setNoticeState("1");
                swAuStDiffNoticeMapper.updateById(swAuStDiffNotice);
            }
        }catch (Exception e){
            log.error("{}",e);
            res.setMsg("下发失败");
            res.setResult(ResultDetailMsg.CHECK_INSERT_ERROR );
        }
        return res;
    }

    /**
     * 通过id列表删除车站差异确认通知
     * 待下发以及已下发的都可以删除，同时如果有补款数据，同时将补款数据删除。
     * @param ids ids
     * @return R
     */
    @ApiOperation(value = "通过id列表删除车站差异确认通知", notes = "通过id列表删除车站差异确认通知")
    @SysLog("通过id列表删除车站差异确认通知" )
    @PreAuthorize("@pms.hasPermission('sw_au_st_diff_notice_del')")
    @GetMapping("/removeStationByIds" )
    public R removeStationByIds(@RequestParam(value = "ids") List<Integer> ids) {
        List<SwAuStDiffNotice> swAuStDiffNotices = swAuStDiffNoticeMapper.selectBatchIds(ids);
        List<Integer> integerList =
                swAuStDiffNotices.stream().map(SwAuStDiffNotice::getRelationid).collect(Collectors.toList());
        //删除车站差异确认通知
        swAuStDiffNoticeMapper.deleteBatchIds(ids);
        //修改车站票款差异信息菜单通知状态改为未加入
        LambdaUpdateWrapper<SwAuStationTicketDifference> updateWrapper =
                Wrappers.<SwAuStationTicketDifference>lambdaUpdate()
                        .set(SwAuStationTicketDifference::getIsAddNotice, "0").in(SwAuStationTicketDifference::getId, integerList);
        swAuStationTicketDifferenceMapper.update(null,updateWrapper);
        //如果有补款数据，同时将补款数据删除。
        LambdaQueryWrapper<SwAuStationShort> wrapper =
                Wrappers.<SwAuStationShort>lambdaQuery().in(SwAuStationShort::getRelationid, ids);
        return R.ok(swAuStationShortMapper.delete(wrapper));
    }

}
